package com.jb.repair.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by gaobin on 2016/1/21.
 */
public class FileUtil {


    /**
     * 将文件解压到到当前文件夹下（适用于只有一个文件的压缩包）
     * @param zipPath
     * @param name
     * @throws IOException
     */
    public static void unzipSingleFileHereWithFileName(String zipPath, String name) throws IOException {
        File zipFile = new File(zipPath);
        File unzipFile = new File(zipFile.getParent() + "/" + name);
        ZipInputStream zipInStream = null;
        FileOutputStream unzipOutStream = null;
        try {
            zipInStream = new ZipInputStream(new FileInputStream(zipFile));
            ZipEntry zipEntry = zipInStream.getNextEntry();
            if (!zipEntry.isDirectory()) {
                unzipOutStream = new FileOutputStream(unzipFile);
                byte[] buf = new byte[4096];
                int len = -1;
                while((len = zipInStream.read(buf)) != -1){
                    unzipOutStream.write(buf, 0, len);
                }
            }
        } finally {
            if(unzipOutStream != null){
                unzipOutStream.close();
            }

            if (zipInStream != null) {
                zipInStream.close();
            }
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param path
     * @param fileName
     * @return
     */
    public static boolean fileExists(String path, String fileName) {
        File file = new File(path, fileName);
        if (file.exists())
            return true;
        return false;
    }

}
